<template>
    <el-card style="margin: auto;">
        <el-form :model="PasswordSet" label-width="auto" style="max-width: 600px; margin: auto;">
            <el-form-item label="旧密码">
                <el-input v-model="PasswordSet.OldPassword" type="password" placeholder="输入旧密码"/>
            </el-form-item>
            <el-form-item label="新密码">
                <el-input v-model="PasswordSet.NewPassword" type="password" placeholder="输入新密码"/>
            </el-form-item>
            <el-form-item label="确认新密码">
                <el-input v-model="PasswordSet.ConfirmPassword" type="password" placeholder="确认新密码"/>
            </el-form-item>
        </el-form>
        <div style="display: flex; justify-content: center;">
            <el-button type="primary" style="width: 200px;" @click="SubmitPassword">确认</el-button>
        </div>
    </el-card>

</template>

<script lang='ts' setup name='SettingPassword'>

// 导入必要组件
import { reactive, ref, watch, onMounted } from 'vue'
import { Search } from '@element-plus/icons-vue'
import axios from 'axios'
import { ElNotification, ElMessage } from 'element-plus'
import { useUserStore } from '@/store/user'

// 生命周期钩子
onMounted(async () => {
    await GetUserPassword();
});

// 密码
let PasswordSet = reactive({
    OldPassword: "",
    NewPassword: "",
    ConfirmPassword: ""
})

let userStore = useUserStore()

// 密码提交回调
function SubmitPassword(){
    if(PasswordSet.OldPassword == ""){
        ElNotification.error({ title: '错误', message: "密码为空" })
    }
    else if(userStore.UserPassword != PasswordSet.OldPassword){
        ElNotification.error({ title: '错误', message: "密码不正确" })
    }
    else if(PasswordSet.ConfirmPassword != PasswordSet.NewPassword){
        ElNotification.error({ title: '错误', message: "新密码不一致" })
    }
    else{
        PutUserPassword()
    }
}

// GET ------------------------------------------ GET //

// GET: 获取的用户密码
let GetPasswordData = ref({
    userName: "",
    userPassword: ""
})

// GET: 获取用户密码
async function GetUserPassword(){
	try {

        // url todo..
		const response = await axios.get(`/api/employee/${userStore.UserName}`);
		GetPasswordData.value = response.data.data || [];
        PasswordSet.OldPassword = GetPasswordData.value.userPassword
	} catch (error) {
		ElNotification({
            title: '错误',
            message: '获取密码失败',
            type: 'error'
		});
	}
}

// PUT ------------------------------------------ PUT //

// PUT: 修改的用户密码
let PutPasswordData = ref({
    userName: "",
    userPassword: ""
})

// PUT: 获取用户密码
async function PutUserPassword(){
    try {
        await axios.put(`/api/employee/${userStore.UserName}`, PutPasswordData);
    } catch (error) {
        ElNotification.error({ message: '修改失败' });
    }
}

</script>

<style scoped>
</style>